/*
 * @Description: 登录验证 Store
 * @Author: xuyang
 * @Date: 2019-06-09 15:06:14 
 * @Last Modified by: XuYang
 * @Last Modified time: 2019-06-17 19:33:51
 */

import { observable, action, computed, runInAction } from 'mobx';
import {
  getCodeApi,
  registerApi,
  loginApi,
  findPasswordApi
} from '../api/login';
class Login {
  @observable user;
  @observable regCode;

  constructor(rootStore) {
    this.rootStore = rootStore;
    storage.load({ key: 'user' }).then((ret) => {
      if (ret) {
        this.setUser(ret);
      }
    }).catch(() => {
      this.setUser(null);
    });
  } 
  /**
   * 设置用户
   * @param {*} newUser 
   */
  @action setUser(newUser) {
    this.user = newUser;
  }
  /**
   * 判断是否登录
   */
  @computed get isLogin() {
    return !!this.user;
  }
  /**
   * 登录
   */
  @action login = async (params,cb) => {
      try { 
          const response = await loginApi(params); 
          if (response.status === 10000) {
            runInAction(() => { 
              storage.save({ key: 'token', data: response.data.token});
              storage.save({ key: 'user', data: response.data.mobile});
              this.setUser(response.data.mobile);
              cb && cb();
            });
          } else {
            this.rootStore.uiStore.setErrorMsg(response.message);
          }
      } catch(e) {
        this.rootStore.uiStore.setErrorMsg(response.message);
      }
  }
  @action getCode = async (params,cb )=> {
    try {
      const response = await getCodeApi(params);
      // console.warn(response);
      if(response.status === 10000){
        runInAction(() =>{
          //获取验证码成功
        })
      }else {
        cb && cb();
      }
    }catch(e){
      this.rootStore.uiStore.setErrorMsg(response.message);
    }
  }
  /**
   * 注册
   */
  @action register = async (params,cb) => {
    try {
        const response = await registerApi(params);
        if (response.status === 10000 ) {
            runInAction(() => { 
                cb(true);
            });
        } else {
            this.rootStore.uiStore.setErrorMsg(response.message);
        }
    } catch(e) {
      this.rootStore.uiStore.setErrorMsg(response.message);
    }
  }
  @action findPassword = async (params,cb) =>{
    try {
      const response = await findPasswordApi(params);
      if (response.status === 10000 ) {
          runInAction(() => { 
              cb(true);
          });
      } else {
          this.rootStore.uiStore.setErrorMsg(response.message);
      }
    } catch(e) {
      this.rootStore.uiStore.setErrorMsg(response.message);
    }
  }

  @action logout = async ()=>{
    this.setUser(null);
  }
  @action.bound loginInvalid = () => {
    // 移除持久化
    storage.remove({ key: 'user' });
    storage.remove({ key: 'token' });
    // 将 Store 中的设置为 null
    this.setUser(null);
  }
}
// const loginStore = new Login();
export default Login;